<template>
  <div class="new-dish">
    <h1>新增菜品</h1>
    <form @submit.prevent="saveDish">
      <label for="dishName">菜品名称:</label>
      <input type="text" id="dishName" v-model="dish.dishName" required><br>
      
      <label for="description">描述:</label>
      <textarea id="description" v-model="dish.description"></textarea><br>
      
      <label for="url">图片URL:</label>
      <input type="text" id="url" v-model="dish.url"><br>
      
      <label for="price">价格:</label>
      <input type="number" id="price" v-model.number="dish.price" step="0.01" required><br>
      
      <label for="merchantId">商家ID:</label>
      <input type="number" id="merchantId" v-model.number="dish.merchantId" required><br>
      
      <button type="submit">保存</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const dish = ref({
  dishId: null,
  dishName: '',
  description: '',
  url: '',
  price: 0,
  merchantId: null
})

const saveDish = async () => {
  try {
    // 验证必填字段
    if (!dish.value.dishName || !dish.value.price || !dish.value.merchantId) {
      alert('请填写所有必填字段')
      return
    }

    // 关键修改：将价格转为字符串传递给后端
    const requestData = {
      ...dish.value,
      price: dish.value.price.toString() // 确保价格以字符串形式传递
    }

    const response = await axios.post('http://localhost:8080/healtheat208/Dish/add', requestData)
    
    if (response.status === 200 && response.data) {
      alert('菜品保存成功')
      router.push({ name: 'dishesList' })
    } else {
      alert('保存失败：' + (response.data.message || '未知错误'))
    }
  } catch (error) {
    console.error('保存失败:', error)
    
    // 增强错误提示
    if (error.response) {
      alert(`服务器错误 (${error.response.status}): ${error.response.data.message || '请检查后端日志'}`)
    } else if (error.request) {
      alert('请求已发送，但没有收到响应')
    } else {
      alert('请求失败：' + error.message)
    }
  }
}
</script>

<style scoped>
.new-dish {
  padding: 20px;
  max-width: 500px;
  margin: 0 auto;
}

form label {
  display: block;
  margin-bottom: 5px;
}

form input,
form textarea {
  width: 100%;
  padding: 8px;
  margin-bottom: 15px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

form button {
  background-color: #4CAF50;
  color: white;
  padding: 10px 15px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

form button:hover {
  background-color: #45a049;
}
</style>